<template>
  <div class="search-wrap">
    <van-search
    v-model="searchInfo"
    show-action
    background="#3396fa"
    placeholder="请输入搜索关键词"
    @search="onSearch"
    @cancel="onCancel"
    @input="onInput"
  />
  <van-cell-group class="search-info">
      <van-cell @click="onSearch(item)" v-show="isShow" v-for="(item,index) in suggestion.options" :key="index" icon="search">{{item}}</van-cell>
  </van-cell-group>
  <div>
    <van-list class="search-content" v-model="state.loading" :finished="state.finished"  finished-text="没有更多了" @load="onLoad">
        <article-item @click="loadDetail(article.art_id)"  v-for="article in suggestion.results" :article="article" :key="article.art_id" />
    </van-list>
  </div>
  </div>
</template>

<script lang="ts" setup>
import { ref,reactive, watch, onMounted,getCurrentInstance, watchEffect } from 'vue'
import { useStore } from 'vuex'
import { useRouter,useRoute  } from 'vue-router'
import ArticleItem from 'components/article_item/index.vue'
import { onInputSearch, onSearchData } from 'api/article'


Components:{ArticleItem}

const router = useRouter()
const route = useRoute()
const store = useStore()

let searchInfo = ref<string>("")
let suggestion = reactive({
    options:[] as Array<any>,
    results:[] as Array<any>
})
let isShow = ref<boolean>(false)
let state = reactive({
    loading:false,
    finished:false,
})

onMounted(() => {
   suggestion.results =  store.state.article.searchList ? store.state.article.searchList : ''
})

watch(() => route,(to,from,next) => {
    console.log(from.name)
})

const onLoad = () => {

}

const loadDetail = (id:number) => {
    router.push({name:"Details",params:{article_id:id}})
}

watch(() => route,() => {
    
})

const onSearch = async (params:any) => {

    isShow.value = false

    state.loading = true

    let resp =  await onSearchData({q:params,per_page:20,page:1})
    state.loading = false

    if(resp && resp.status === 200) {
        let { data } = resp.data

        store.commit('setSearchList',data.results)

        suggestion.results = data.results
    }
}

const onCancel = () => {
    router.back()
}

const onInput = async () => {
    let resp = await onInputSearch({q:searchInfo.value})

    if(resp && resp.status === 200) {
        let { data } = resp.data

        suggestion.options = data.options

        isShow.value = true
    }
    
}
</script>

<style lang="scss" scoped>
    .search-wrap {
        ::v-deep .van-search__content {
            height: 30px;
        }
        ::v-deep .van-search__action {
            color: #fff;
        }

        ::v-deep .van-search__action:active{
            color: #fff;
            background: transparent;
        }

        .search-info {
            z-index: 999;
        }
        .search-content{
            position: fixed;
            left: 0;
            right: 0;
            top: 70px;
            bottom: 1px;
            overflow-y:auto ;
        }
    }
</style>